<template>
  <div>
    <a-form :model="formState" ref="userRole">
      <a-form-item name="roleIds">
        <a-transfer :dataSource="roleList" v-model="formState.roleIds" :listStyle="{ width: '45%', height: '480px' }" :titles="[' 可选角色', ' 已选角色']" :render="(item) => item.title" :target-keys="formState.roleIds" @change="handleTransferChange" filterable show-search></a-transfer>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" name="UserRole" setup>
import { reactive, ref } from 'vue';
import { getAuthRoleList, setUserRole } from '@/views/sys/user/data/user.api';

const userRole = ref();
const roleList = ref();
const userId = ref();
const formState = reactive({
  roleIds: [],
});

/**
 * 设置数据
 * @param data
 */
async function setData(data) {
  userId.value = data.record.userId;
  getAuthRoleList({
    organizationId: data.record.organizationId,
    userId: userId.value,
  }).then((data) => {
    data.roleList.map((item) => {
      item.key = item.roleId;
      item.title = item.roleName;
    });
    roleList.value = data.roleList;
    formState.roleIds = data.roleIds;
  });
}

/**
 * 穿梭框change
 * @param targetKeys
 * @param direction
 * @param moveKeys
 */
function handleTransferChange(targetKeys, direction, moveKeys) {
  formState.roleIds = targetKeys;
}

/**
 * 提交已分配角色
 */
async function handleSubmit(drawerEmit) {
  userRole.value.validate().then(() => {
    setUserRole({
      userId: userId.value,
      roleIds: formState.roleIds.join(','),
    });
  });
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
});
</script>
<style scoped lang="less"></style>
